package top.banner.usercenter.service.user;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.banner.usercenter.dao.bonuseventlog.BonusEventLogMapper;
import top.banner.usercenter.dao.user.UserMapper;
import top.banner.usercenter.domain.dto.messaging.UserAddBonusMsgDTO;
import top.banner.usercenter.domain.dto.user.UserLoginDTO;
import top.banner.usercenter.domain.entity.bonuseventlog.BonusEventLog;
import top.banner.usercenter.domain.entity.user.User;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author XGL
 */
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;
    @Resource
    private BonusEventLogMapper bonusEventLogMapper;

    public User findById(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }


    @Transactional
    public void addBonus(UserAddBonusMsgDTO addBonusMsgDTO) {

        // 当收到消息后，执行业务
        // 用户增加积分
        Integer userId = addBonusMsgDTO.getUserId();
        User user = userMapper.selectByPrimaryKey(userId);
        Integer bonus = addBonusMsgDTO.getBonus();
        user.setBonus(user.getBonus() + bonus);
        userMapper.updateByPrimaryKey(user);

        //记录日志到bonus_event_log表里面
        bonusEventLogMapper.insert(
                BonusEventLog.builder()
                        .userId(userId)
                        .value(bonus)
                        .event("投稿")
                        .createTime(new Date())
                        .description("投稿加积分")
                        .build()
        );
    }

    /**
     * 如果用户是否注册，没有注册就注册
     */
    public User login(UserLoginDTO loginDTO, String openId) {

        User user = userMapper.selectOne(
                User.builder()
                        .wxId(openId)
                        .build()
        );

        if (user == null) {
            final Date date = new Date();
            user = User.builder()
                    .wxId(openId)
                    .bonus(300)
                    .wxNickname(loginDTO.getWxNickname())
                    .avatarUrl(loginDTO.getAvatarUrl())
                    .roles("user")
                    .createTime(date)
                    .updateTime(date)
                    .build();
            userMapper.insertSelective(user);
        }
        return user;
    }
}
